package org.linlinjava.litemall.wx.service;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.sun.xml.bind.v2.TODO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.express.ExpressService;
import org.linlinjava.litemall.core.kdniao.dto.KdniaoOrderTraceResultDto;
import org.linlinjava.litemall.core.kdniao.dto.Order;
import org.linlinjava.litemall.core.kdniao.service.KdniaoService;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.qcode.QCodeService;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.core.util.DateTimeUtil;
import org.linlinjava.litemall.core.util.IpUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.wx.dto.AnalysisOrderResult;
import org.linlinjava.litemall.wx.dto.GoodsProductSimpleDto;
import org.linlinjava.litemall.wx.dto.OrderRequest;
import org.linlinjava.litemall.wx.dto.PayInfo;
import org.linlinjava.litemall.wx.task.OrderUnpaidTask;
import org.linlinjava.litemall.wx.task.RentNotReturnOrderUnpaidTask;
import org.linlinjava.litemall.wx.util.SnUtil;
import org.linlinjava.litemall.wx.vo.RentNotReturnOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.wx.util.WxResponseCode.*;

/**
 * 订单服务
 *
 * <p>WxExpressService
 * 订单状态：
 * 101 订单生成，未支付；102，下单后未支付用户取消；103，下单后未支付超时checkPayInfo系统自动取消
 * 201 支付完成，商家未发货；202，订单生产，已付款未发货，但是退款取消；
 * 301 商家发货，用户未确认；
 * 401 用户确认收货； 402 用户没有确认收货超过一定时间，系统自动确认收货；
 *
 * <p>
 * 用户操作：
 * 当101用户未付款时，此时用户可以进行的操作是取消订单，或者付款操作
 * 当201支付完成而商家未发货时，此时用户可以取消订单并申请退款
 * 当301商家已发货时，此时用户可以有确认收货的操作
 * 当401用户确认收货以后，此时用户可以进行的操作是删除订单，评价商品，申请售后，或者再次购买
 * 当402系统自动确认收货以后，此时用户可以删除订单，评价商品，申请售后，或者再次购买
 */
@Service("order-pay")
public class WxOrderService implements PayProcessor {
    private final Log logger = LogFactory.getLog(WxOrderService.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private LitemallAddressService addressService;
    @Autowired
    private LitemallCartService cartService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private LitemallGrouponRulesService grouponRulesService;
    @Autowired
    private LitemallGrouponService grouponService;
    @Autowired
    private LitemallSpellService spellService;
    @Autowired
    private QCodeService qCodeService;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private LitemallCommentService commentService;
    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private LitemallAftersaleService aftersaleService;
    @Autowired
    private WxBenefitService wxBenefitService;
    @Autowired
    private WxSpellService wxSpellService;
    @Autowired
    private LitemallRentOrderDetailService rentOrderDetailService;
    @Autowired
    private LitemallRentOrderService rentOrderService;
    @Autowired
    private LitemallMemberRuleService memberRuleService;
    @Autowired
    private LitemallUserMemberService userMemberService;

    @Autowired
    private WxTeamService wxTeamService;
    @Autowired
    private OrderAnalysis orderAnalysis;
    @Autowired
    private KdniaoService kdniaoService;

    /**
     * 订单列表
     *
     * @param userId   用户ID
     * @param showType 订单信息：
     *                 0，全部订单；
     *                 1，待付款；
     *                 2，待发货；
     *                 3，待收货；
     *                 4，待评价；
     *                 5,已取消；
     *                 9，待分享
     * @param page     分页页数
     * @param limit    分页大小
     * @return 订单列表
     */
    public Object list(Integer userId, Integer showType, Integer page, Integer limit, String sort, String order) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallOrder> orderList;
        if (showType.equals(9)) { // 待分享专用
            Short spellStatus = OrderUtil.spellStatus(showType);
            orderList = orderService.queryBySpellStatusAndOrderStatus(userId, spellStatus, OrderUtil.canSellOrderStatus(), page, limit, sort, order);
        } else {
            List<Short> orderStatus = OrderUtil.orderStatus(showType);
            orderList = orderService.queryByOrderStatus(userId, orderStatus, page, limit, sort, order);
        }

        List<Map<String, Object>> orderVoList = new ArrayList<>(orderList.size());
        for (LitemallOrder o : orderList) {
            orderVoList.add(orderListInfo(o));
        }

        return ResponseUtil.okList(orderVoList, orderList);
    }

    /**
     * 刷新某一订单
     *
     * @param orderId
     * @return
     */
    public Object refreshItem(Integer userId, Integer orderId) {
        LitemallOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.fail();
        }
        if (!userId.equals(order.getUserId())) {
            return ResponseUtil.fail();
        }
        if (order.getDeleted()) { // 订单已删除
            return ResponseUtil.ok();
        }
        return ResponseUtil.ok(orderListInfo(order));
    }

    /**
     * 整理订单列表所需信息
     *
     * @param o
     * @return
     */
    private Map<String, Object> orderListInfo(LitemallOrder o) {
        Map<String, Object> orderVo = new HashMap<>();
        orderVo.put("id", o.getId());
        orderVo.put("orderSn", o.getOrderSn());
        orderVo.put("goodsPrice", o.getGoodsPrice());
        orderVo.put("freightPrice", o.getFreightPrice());
        orderVo.put("actualPrice", o.getActualPrice());
        orderVo.put("orderStatusText", OrderUtil.orderStatusText(o));
        orderVo.put("handleOption", OrderUtil.build(o));
        orderVo.put("aftersaleStatus", o.getAftersaleStatus());
        orderVo.put("comments", o.getComments());
        orderVo.put("addTime", o.getAddTime());

        LitemallGroupon groupon = grouponService.queryByOrderId(o.getId());
        if (groupon != null) {
            orderVo.put("isGroupin", true);
        } else {
            orderVo.put("isGroupin", false);
        }

        LitemallSpell spell = spellService.queryInitiatorByOrderId(o.getId());
        if (spell != null) {
            orderVo.put("spellId", spell.getId());
        }
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(o.getId());
        List<Map<String, Object>> orderGoodsVoList = new ArrayList<>(orderGoodsList.size());
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Map<String, Object> orderGoodsVo = new HashMap<>();
            orderGoodsVo.put("id", orderGoods.getId());
            orderGoodsVo.put("goodsId", orderGoods.getGoodsId());
            orderGoodsVo.put("submitgoodsName", orderGoods.getGoodsName());
            orderGoodsVo.put("number", orderGoods.getNumber());
            orderGoodsVo.put("picUrl", orderGoods.getPicUrl());
            orderGoodsVo.put("specifications", orderGoods.getSpecifications());
            orderGoodsVo.put("price", orderGoods.getPrice());
            orderGoodsVoList.add(orderGoodsVo);
        }
        orderVo.put("goodsList", orderGoodsVoList);
        return orderVo;
    }

    /**
     * 订单简单详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return 简单详情
     */
    public Object simpleDetail(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        // 订单信息
        LitemallOrder order = orderService.findById(userId, orderId);
        if (null == order) {
            return ResponseUtil.fail(ORDER_UNKNOWN, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(ORDER_INVALID, "不是当前用户的订单");
        }
        return ResponseUtil.ok(order);

    }

    /**
     * 订单结束查看详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return 简单详情
     */
    public Object result(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        // 订单信息
        LitemallOrder order = orderService.findById(userId, orderId);
        if (null == order) {
            return ResponseUtil.fail(ORDER_UNKNOWN, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(ORDER_INVALID, "不是当前用户的订单");
        }
        LitemallOrderGoods orderGoods = orderGoodsService.queryOneGoodsByOid(orderId);
        HashMap<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderGoods", orderGoods);
        LitemallSpell spell = spellService.queryInitiatorByOrderId(order.getId());
        result.put("spell", spell);
        return ResponseUtil.ok(result);

    }

    /**
     * 订单详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return 订单详情
     */
    public Object detail(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        // 订单信息
        LitemallOrder order = orderService.findById(userId, orderId);
        if (null == order) {
            return ResponseUtil.fail(ORDER_UNKNOWN, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(ORDER_INVALID, "不是当前用户的订单");
        }
        Map<String, Object> orderVo = new HashMap<String, Object>();
        orderVo.put("id", order.getId());
        orderVo.put("orderSn", order.getOrderSn());
        orderVo.put("message", order.getMessage());
        orderVo.put("addTime", order.getAddTime());
        orderVo.put("payTime", order.getPayTime());
        orderVo.put("shipTime", order.getShipTime());
        orderVo.put("consignee", order.getConsignee());
        orderVo.put("mobile", order.getMobile());
        orderVo.put("address", order.getAddress());
        orderVo.put("goodsPrice", order.getGoodsPrice());
        orderVo.put("couponPrice", order.getCouponPrice());
        orderVo.put("freightPrice", order.getFreightPrice());
        orderVo.put("discount", order.getDiscount());
        orderVo.put("bonusPrice", order.getIntegralPrice());
        orderVo.put("spellPrice", order.getSpellPrice());
        orderVo.put("actualPrice", order.getActualPrice());
        orderVo.put("orderStatusText", OrderUtil.orderStatusText(order));
        orderVo.put("handleOption", OrderUtil.build(order));
        orderVo.put("aftersaleStatus", order.getAftersaleStatus());
        orderVo.put("expCode", order.getShipChannel());
        orderVo.put("expName", order.getShipChannelName());
        orderVo.put("expNo", order.getShipSn());
        orderVo.put("expWay", order.getShipWay());
        orderVo.put("expTime", order.getShipTime());

        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", orderVo);
        result.put("orderGoods", orderGoodsList);

        Map<String, Object> spell = wxSpellService.detailByOrder(order.getId());
        result.put("spell", spell);

//        // 订单状态为已发货且物流信息不为空
//        //"YTO", "800669400640887922"
//        if (order.getOrderStatus().equals(OrderUtil.STATUS_SHIP) || order.getOrderStatus().equals(OrderUtil.STATUS_CONFIRM)) {
//            if (order.getShipWay().equals(ShipWayConstant.SHIP_WAY_EXPRESS)) {
//                try {
//                    KdniaoOrderTraceResultDto expressInfo = kdniaoService.getOrderTracesByJson(new Order(order.getId().toString(), order.getShipChannel(), order.getShipSn()));
//                    result.put("expressInfo",expressInfo);
//                } catch (Exception e) {
//                    result.put("expressInfo", "获取物流轨迹失败");
//                }
//            } else {
//                result.put("expressInfo", "同城配送，今日必达");
//            }
//        } else {
//            result.put("expressInfo", new ArrayList<>());
//        }
        return ResponseUtil.ok(result);
    }


    /**
     * 提交订单
     * <p>
     * 1. 创建订单表项和订单商品表项;
     * 2. 购物车清空;
     * 3. 优惠券设置已用;
     * 4. 商品货品库存减少;
     * 5. 如果是团购商品，则创建团购活动表项。
     *
     * @param userId  用户ID
     * @param request 订单信息，{ cartId：xxx, addressId: xxx, couponId: xxx, message: xxx, grouponRulesId: xxx,  grouponLinkId: xxx}
     * @return 提交订单操作结果
     */
    @Transactional
    public Object submit(Integer userId, @RequestBody OrderRequest request) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        if (request.getCartId() == null || request.getAddressId() == null || request.getCouponId() == null) {
            return ResponseUtil.badArgument();
        }

        // 收货地址
        LitemallAddress checkedAddress = addressService.query(userId, request.getAddressId());
        if (checkedAddress == null) {
            return ResponseUtil.badArgument();
        }

        AnalysisOrderResult analysis = orderAnalysis.analysis(userId, request, false);

        Integer orderId = null;
        LitemallOrder order = null;
        // 订单
        order = new LitemallOrder();
        order.setType(1);
        order.setUserId(userId);
        order.setNickname(userService.findById(userId).getNickname());
        order.setOrderSn(orderService.generateOrderSn(userId));
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setConsignee(checkedAddress.getName());
        order.setMobile(checkedAddress.getTel());
        order.setMessage(request.getMessage());
        String detailedAddress = checkedAddress.getProvince() + " " + checkedAddress.getCity() + " " + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
        order.setAddress(detailedAddress);
        order.setGoodsPrice(analysis.getCheckedGoodsPrice());
        order.setFreightPrice(analysis.getFreightPrice());
        order.setCouponPrice(analysis.getCouponPrice());
        order.setSpellPrice(analysis.getSpellPrice());
        order.setIntegralPrice(analysis.getIntegralPrice());
        order.setOrderPrice(analysis.getOrderTotalPrice());
        order.setActualPrice(analysis.getActualPrice());
        order.setDiscount(analysis.getDiscount());
        order.setSource(request.getSource()); // 添加分享人
        int compare = analysis.getSpellPrice().compareTo(BigDecimal.ZERO);
        if (analysis.getInvolveSpell() != null && !analysis.getInvolveSpell() && analysis.getSpellPrice() != null && compare > 0) { // 如果未参与拼单, 且有有拼单返利(单商品并且商品设置返利)，则待分享
            order.setSpellStatus(OrderSpellConstant.STATUS_WAIT); //订单标识待分享
        }

        // 添加订单表项
        orderService.add(order);
        orderId = order.getId();

        LitemallUserMember userMember = userMemberService.findByUid(userId);
        if (userMember != null) {
            for (LitemallCart cartGoods : analysis.getCheckedGoodsList()) {
                // 订单商品
                LitemallOrderGoods orderGoods = new LitemallOrderGoods();
                orderGoods.setOrderId(order.getId());
                orderGoods.setGoodsId(cartGoods.getGoodsId());
                orderGoods.setGoodsSn(cartGoods.getGoodsSn());
                orderGoods.setProductId(cartGoods.getProductId());
                orderGoods.setGoodsName(cartGoods.getGoodsName());
                orderGoods.setPicUrl(cartGoods.getPicUrl());
                orderGoods.setPrice(cartGoods.getMemberPrice());
                orderGoods.setNumber(cartGoods.getNumber());
                orderGoods.setSpecifications(cartGoods.getSpecifications());
                orderGoods.setAddTime(LocalDateTime.now());

                orderGoodsService.add(orderGoods);
            }
        } else {
            // 添加订单商品表项
            for (LitemallCart cartGoods : analysis.getCheckedGoodsList()) {
                // 订单商品
                LitemallOrderGoods orderGoods = new LitemallOrderGoods();
                orderGoods.setOrderId(order.getId());
                orderGoods.setGoodsId(cartGoods.getGoodsId());
                orderGoods.setGoodsSn(cartGoods.getGoodsSn());
                orderGoods.setProductId(cartGoods.getProductId());
                orderGoods.setGoodsName(cartGoods.getGoodsName());
                orderGoods.setPicUrl(cartGoods.getPicUrl());
                orderGoods.setPrice(cartGoods.getPrice());
                orderGoods.setNumber(cartGoods.getNumber());
                orderGoods.setSpecifications(cartGoods.getSpecifications());
                orderGoods.setAddTime(LocalDateTime.now());

                orderGoodsService.add(orderGoods);
            }
        }
        // 删除购物车里面的商品信息
        cartService.clearGoods(userId);

        // 商品货品数量减少
        for (LitemallCart checkGoods : analysis.getCheckedGoodsList()) {
            Integer productId = checkGoods.getProductId();
            LitemallGoodsProduct product = productService.findById(productId);

            int remainNumber = product.getNumber() - checkGoods.getNumber();
            if (remainNumber < 0) {
                throw new RuntimeException("下单的商品货品数量大于库存量");
            }
            if (productService.reduceStock(productId, checkGoods.getNumber()) == 0) {
                throw new RuntimeException("商品货品库存减少失败");
            }
        }

        // 如果使用了优惠券，设置优惠券使用状态
        if (request.getCouponId() != 0 && request.getCouponId() != -1) {
            couponUserService.use(request.getUserCouponId(), orderId);
        }

//        //如果是团购项目，添加团购信息
//        Integer grouponRulesId = request.getGrouponRulesId();
//        Integer grouponLinkId = request.getGrouponLinkId();
//        if (grouponRulesId != null && grouponRulesId > 0) {
//            LitemallGroupon groupon = new LitemallGroupon();
//            groupon.setOrderId(orderId);
//            groupon.setStatus(GrouponConstant.STATUS_NONE);
//            groupon.setUserId(userId);
//            groupon.setRulesId(grouponRulesId);
//            if (grouponLinkId != null && grouponLinkId > 0) {//参与者
//                //参与的团购记录
//                LitemallGroupon baseGroupon = grouponService.queryById(grouponLinkId);
//                groupon.setCreatorUserId(baseGroupon.getCreatorUserId());
//                groupon.setGrouponId(grouponLinkId);
//                groupon.setShareUrl(baseGroupon.getShareUrl());
//                grouponService.createGroupon(groupon);
//                grouponLinkId = groupon.getId();
//            } else { // 发起者
//                groupon.setCreatorUserId(userId);
//                groupon.setCreatorUserTime(LocalDateTime.now());
//                groupon.setGrouponId(0);
//                grouponService.createGroupon(groupon);
//                grouponLinkId = groupon.getId();
//                taskService.addTask(new GrouponUnpaidTask(grouponLinkId));
//            }
//        }
        // 如果是参与拼单，参与拼单记录
//        if (analysis.getInvolveSpell()) {
//            if (wxSpellService.involve(analysis.getSpell(), userId, orderId) == null) {
//                return ResponseUtil.fail(400, "当前拼单已结束");
//            }
//        }

        // 订单支付超期任务
        taskService.addTask(new OrderUnpaidTask(orderId));

        Integer bonus = request.getBonus();
        // 如果使用了积分修改积分
//        if (bonus != null && bonus > 0) {
//            memberService.cutBonus(userId, bonus, order.getOrderSn());
//        }

        Map<String, Object> data = new HashMap<>();
        data.put("orderId", orderId);
//        if (grouponRulesId != null && grouponRulesId > 0) {
//            data.put("grouponLinkId", grouponLinkId);
//        } else {
//            data.put("grouponLinkId", 0);
//        }
        return ResponseUtil.ok(data);
    }

    /**
     * 提交不想还书订单
     *
     * @param userId
     * @param goodsProductSimpleDtos
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object submitRentNotReturnOrder(Integer userId, GoodsProductSimpleDto[] goodsProductSimpleDtos) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (goodsProductSimpleDtos == null || goodsProductSimpleDtos.length == 0) {
            return ResponseUtil.fail(400, "请至少选择一本书");
        }

        BigDecimal totalFee = BigDecimal.ZERO;
        BigDecimal memberDiscount = BigDecimal.ONE;
        LitemallUserMember userMember = userMemberService.findByUid(userId);
        if (userMember != null) {
            Integer memberRuleId = userMember.getMemberRuleId();
            LitemallMemberRule memberRule = memberRuleService.findById(memberRuleId);
            memberDiscount = memberRule.getDiscount();
        }
        LitemallOrder order = new LitemallOrder();
        LitemallAddress address = addressService.findDefault(userId);
        if (address != null) {
            order.setConsignee(address.getName());
            order.setMobile(address.getTel());
            String detailedAddress = address.getProvince() + " " + address.getCity() + " " + address.getCounty() + " " + address.getAddressDetail();
            order.setAddress(detailedAddress);
        }
        order.setNickname(userService.findById(userId).getNickname());
        order.setType(2);
        order.setOrderStatus(OrderUtil.STATUS_CREATE);
        order.setUserId(userId);
        order.setDiscount(memberDiscount);
        order.setOrderSn(SnUtil.generateOrderSn());
        order.setAddTime(LocalDateTime.now());
        order.setFreightPrice(BigDecimal.ZERO);
        order.setCouponPrice(BigDecimal.ZERO);
        order.setSpellPrice(BigDecimal.ZERO);
        order.setIntegralPrice(BigDecimal.ZERO);
        order.setOrderPrice(totalFee);
        order.setActualPrice(totalFee);
        orderService.add(order);

        for (GoodsProductSimpleDto goodsProductSimpleDto : goodsProductSimpleDtos) {
            Integer goodsProductId = goodsProductSimpleDto.getGoodsProductId();
            Integer number = goodsProductSimpleDto.getNumber();
            if (number.equals(0)) {
                return ResponseUtil.fail(400, "购买数量不能为0");
            }
            LitemallGoodsProduct goodsProduct = productService.findById(goodsProductId);
            LitemallGoods goods = goodsService.findById(goodsProduct.getGoodsId());
            LitemallRentOrderDetail rentOrderDetail = rentOrderDetailService.queryByUidAndGoodsProductId(userId, goodsProductId);
            if (rentOrderDetail == null) {
                return ResponseUtil.fail(400, "非法请求");
            }
            if (rentOrderDetail.getNumber() < number) {
                return ResponseUtil.fail(400, "非法请求");
            }
            LitemallOrderGoods orderGoods = new LitemallOrderGoods();
            orderGoods.setGoodsName(goods.getName());
            orderGoods.setSpecifications(goodsProduct.getSpecifications());
            orderGoods.setGoodsSn(goods.getGoodsSn());
            orderGoods.setPicUrl(goods.getPicUrl());
            orderGoods.setNumber(number);
            orderGoods.setPrice(goods.getNationalUnifiedPrice().multiply(memberDiscount).multiply(BigDecimal.valueOf(number)));
            orderGoods.setProductId(goodsProductId);
            orderGoods.setGoodsId(goodsProduct.getGoodsId());
            orderGoods.setOrderId(order.getId());
            orderGoodsService.add(orderGoods);
            totalFee = totalFee.add(goods.getNationalUnifiedPrice().multiply(memberDiscount).multiply(BigDecimal.valueOf(number)));
        }
        order.setOrderPrice(totalFee);
        order.setGoodsPrice(totalFee);
        order.setActualPrice(totalFee);
        orderService.updateById(order);

        taskService.addTask(new RentNotReturnOrderUnpaidTask(order.getId(), 30 * 60 * 1000L));

        Map<String, Object> data = new HashMap<>(5);
        data.put("orderId", order.getId());
        data.put("orderSn", order.getOrderSn());
        data.put("totalFee", totalFee);
        return data;
    }

    public Object listRentNotReturnIndex(Integer userId, Integer rentOrderId) {
        List<RentNotReturnOrderVO> rentNotReturnOrderVOList = new ArrayList<>();
        LitemallRentOrder rentOrder = rentOrderService.findById(rentOrderId);
        if (!rentOrder.getRentOrderStatus().equals(RentOrderConstant.STATUS_CONFIRM)) {
            return ResponseUtil.fail(400, "该订单尚未确认收货");
        }
        List<LitemallRentOrderDetail> rentOrderDetailList = rentOrderDetailService.queryByOid(rentOrderId);
        for (LitemallRentOrderDetail rentOrderDetail : rentOrderDetailList) {
            RentNotReturnOrderVO rentNotReturnOrderVO = new RentNotReturnOrderVO();
            LitemallGoodsProduct product = productService.findById(rentOrderDetail.getGoodsProductId());
            if (product != null) {
                LitemallGoods goods = goodsService.findById(product.getGoodsId());
                if (goods != null) {
                    rentNotReturnOrderVO.setGoodsId(goods.getId());
                    rentNotReturnOrderVO.setAuthor(goods.getAuthor());
                    rentNotReturnOrderVO.setName(goods.getName());
                    rentNotReturnOrderVO.setGoodsProductId(product.getId());
                    rentNotReturnOrderVO.setNationalUnifiedPrice(goods.getNationalUnifiedPrice());
                    BigDecimal memberDiscount = BigDecimal.ONE;
                    LitemallUserMember userMember = userMemberService.findByUid(userId);
                    if (userMember != null) {
                        Integer memberRuleId = userMember.getMemberRuleId();
                        LitemallMemberRule memberRule = memberRuleService.findById(memberRuleId);
                        memberDiscount = memberRule.getDiscount();
                    }
                    rentNotReturnOrderVO.setDiscountPrice(goods.getNationalUnifiedPrice().multiply(memberDiscount).setScale(2, RoundingMode.HALF_EVEN));
                    rentNotReturnOrderVO.setPublisher(goods.getPublisher());
                    rentNotReturnOrderVO.setNumber(rentOrderDetail.getNumber());
                    rentNotReturnOrderVO.setPicUrl(goods.getPicUrl());
                    rentNotReturnOrderVOList.add(rentNotReturnOrderVO);
                }
            }

        }
        return ResponseUtil.ok(rentNotReturnOrderVOList);
    }

    /**
     * 取消订单
     * <p>
     * 1. 检测当前订单是否能够取消；
     * 2. 设置订单取消状态；
     * 3. 商品货品库存恢复；
     * 4. TODO 优惠券；
     *
     * @param userId  用户ID
     * @param orderId 订单信息，{ orderId：xxx }
     * @return 取消订单操作结果
     */
    @Transactional
    public Object cancel(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgumentValue();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        // 检测是否能够取消
        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isCancel()) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能取消");
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_CANCEL);
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Integer productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (productService.addStock(orderGoods.getGoodsId(), (number)) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }

        // 接触参与拼单信息
        wxSpellService.breakInvolve(orderId);

        return ResponseUtil.ok();
    }

    /**
     * 微信H5支付
     *
     * @param userId
     * @param body
     * @param request
     * @return
     */
    @Transactional
    public Object h5pay(Integer userId, String body, HttpServletRequest request) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgumentValue();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        // 检测是否能够取消
        OrderHandleOption handleOption = OrderUtil.build(order);
        if (handleOption.isPay()) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能支付");
        }

        WxPayMwebOrderResult result = null;
        try {
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setOutTradeNo(order.getOrderSn());
            orderRequest.setTradeType("MWEB");
            orderRequest.setBody("订单：" + order.getOrderSn());
            // 元转成分
            int fee = 0;
            BigDecimal actualPrice = order.getActualPrice();
            fee = actualPrice.multiply(new BigDecimal(100)).intValue();
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(IpUtil.getIpAddr(request));

            result = wxPayService.createOrder(orderRequest);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseUtil.ok(result);
    }

    /**
     * 记录订单成功(由于新增余额支付，所以单提出)
     *
     * @param orderSn
     * @return
     */
    @Override
    public Object recordSuccess(String orderSn) {
        return recordSuccess(orderSn, null, null);
    }

    /**
     * 记录订单成功(由于新增余额支付，所以单提出)
     *
     * @param orderSn
     * @param totalFee
     * @param payId
     * @return
     */
    @Override
    public Object recordSuccess(String orderSn, String totalFee, String payId) {
        LitemallOrder order = orderService.findBySn(orderSn);
        if (order == null) {
            return WxPayNotifyResponse.fail("订单不存在 sn=" + orderSn);
        }

        if (totalFee == null) {
            totalFee = order.getActualPrice().toString();
        }

        // 检查这个订单是否已经处理过
        if (OrderUtil.hasPayed(order)) {
            return WxPayNotifyResponse.success("订单已经处理成功!");
        }

        // 检查支付订单金额
        if (!totalFee.equals(order.getActualPrice().toString())) {
            return WxPayNotifyResponse.fail(order.getOrderSn() + " : 支付金额不符合 totalFee=" + totalFee);
        }

        order.setPayId(payId);
        order.setPayTime(LocalDateTime.now());

        if (order.getType() == 1) {
            order.setOrderStatus(OrderUtil.STATUS_PAY);
            //  支付成功，有团购信息，更新团购信息
            LitemallGroupon groupon = grouponService.queryByOrderId(order.getId());
            if (groupon != null) {
                LitemallGrouponRules grouponRules = grouponRulesService.findById(groupon.getRulesId());

                //仅当发起者才创建分享图片
                if (groupon.getGrouponId() == 0) {
                    String url = qCodeService.createGrouponShareImage(grouponRules.getGoodsName(), grouponRules.getPicUrl(), groupon);
                    groupon.setShareUrl(url);
                }
                groupon.setStatus(GrouponConstant.STATUS_ON);
                if (grouponService.updateById(groupon) == 0) {
                    return WxPayNotifyResponse.fail("更新数据已失效");
                }

                List<LitemallGroupon> grouponList = grouponService.queryJoinRecord(groupon.getGrouponId());
                if (groupon.getGrouponId() != 0 && (grouponList.size() >= grouponRules.getDiscountMember() - 1)) {
                    for (LitemallGroupon grouponActivity : grouponList) {
                        grouponActivity.setStatus(GrouponConstant.STATUS_SUCCEED);
                        grouponService.updateById(grouponActivity);
                    }

                    LitemallGroupon grouponSource = grouponService.queryById(groupon.getGrouponId());
                    grouponSource.setStatus(GrouponConstant.STATUS_SUCCEED);
                    grouponService.updateById(grouponSource);
                }
            }

            // 如果可拼单则开启拼单
            if (OrderSpellConstant.STATUS_WAIT.equals(order.getSpellStatus())) {
                wxSpellService.open(order.getUserId(), order.getId());
            } else {// 支付成功如果是参加拼单订单，更新拼单信息并返钱
                wxSpellService.finish(order.getId());
            }

            //TODO 发送邮件和短信通知，这里采用异步发送
            // 订单支付成功以后，会发送短信给用户，以及发送邮件给管理员
            notifyService.notifyMail("新订单通知", order.toString());
            // 这里微信的短信平台对参数长度有限制，所以将订单号只截取后6位
            notifyService.notifySmsTemplateSync(order.getMobile(), NotifyType.PAY_SUCCEED, new String[]{orderSn.substring(8, 14)});

            // 请依据自己的模版消息配置更改参数
            String[] parms = new String[]{
                    order.getOrderSn(),
                    order.getOrderPrice().toString(),
                    DateTimeUtil.getDateTimeDisplayString(order.getAddTime()),
                    order.getConsignee(),
                    order.getMobile(),
                    order.getAddress()
            };

            // 取消订单超时未支付任务
            taskService.removeTask(new OrderUnpaidTask(order.getId()));

//            // 记录分享收益
//            if (order.getSource() != null) {
//                wxBenefitService.share(IDHelper.decrypt(order.getSource()), order.getUserId(), BenefitEventConstant.SHARE_ORDER, order.getOrderSn(), order.getActualPrice());
//            }
        }
        if (order.getType() == 2) {
            order.setOrderStatus(OrderUtil.STATUS_CONFIRM);
            List<LitemallOrderGoods> litemallOrderGoods = orderGoodsService.queryByOid(order.getId());
            Integer orderId = 0;
            for (LitemallOrderGoods litemallOrderGood : litemallOrderGoods) {
                LitemallRentOrderDetail rentOrderDetail = rentOrderDetailService.queryByUidAndGoodsProductId(order.getUserId(), litemallOrderGood.getProductId());
                if (rentOrderDetail == null) {
                    return ResponseUtil.fail(400, "非法请求参数");
                }
                orderId = rentOrderDetail.getRentOrderId();
                if (rentOrderDetail.getNumber() > litemallOrderGood.getNumber()) {
                    rentOrderDetail.setNumber(rentOrderDetail.getNumber() - litemallOrderGood.getNumber());
                    rentOrderDetailService.updateById(rentOrderDetail);
                } else if (rentOrderDetail.getNumber().equals(litemallOrderGood.getNumber())) {
                    rentOrderDetailService.deleteById(rentOrderDetail.getId());
                }

            }
            LitemallRentOrder rentOrder = rentOrderService.findById(orderId);
            if (rentOrder == null) {
                return ResponseUtil.fail(400, "rentOrder为空");
            }
            List<LitemallRentOrderDetail> rentOrderDetails = rentOrderDetailService.queryByOid(orderId);
            if (rentOrderDetails == null || rentOrderDetails.size() == 0) {
                rentOrder.setDeleted(true);
                rentOrderService.updateById(rentOrder);
            }
            taskService.removeTask(new RentNotReturnOrderUnpaidTask(order.getId(), 30 * 60 * 1000L));
        }
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            return WxPayNotifyResponse.fail("更新数据已失效");
        }
        LitemallUser user = userService.findById(order.getUserId());
        user.setCostMoney(user.getCostMoney().add(order.getActualPrice()));
        userService.updateWithOptimisticLocker(user);
        return WxPayNotifyResponse.success("处理成功!");
    }

    /**
     * 订单申请退款
     * <p>
     * 1. 检测当前订单是否能够退款；
     * 2. 设置订单申请退款状态。
     *
     * @param userId  用户ID
     * @param orderId 订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    public Object refund(Integer userId, Integer orderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isRefund()) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能取消");
        }

        // 设置订单申请退款状态
        order.setOrderStatus(OrderUtil.STATUS_REFUND);
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            return ResponseUtil.updatedDateExpired();
        }

        // 拼单信息(如果有拼单，拼单失败)
        LitemallSpell spell = spellService.queryByOrderId(orderId);
        if (spell != null) {
            wxSpellService.fail(spell.getId());
        }

        //TODO 发送邮件和短信通知，这里采用异步发送
        // 有用户申请退款，邮件通知运营人员
        notifyService.notifyMail("退款申请", order.toString());

        return ResponseUtil.ok();
    }

    /**
     * 确认收货
     * <p>
     * 1. 检测当前订单是否能够确认收货；
     * 2. 设置订单确认收货状态。
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    public Object confirm(Integer userId, String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isConfirm()) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能确认收货");
        }

        Short comments = orderGoodsService.getComments(orderId);
        order.setComments(comments);

        order.setOrderStatus(OrderUtil.STATUS_CONFIRM);
        order.setConfirmTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            return ResponseUtil.updatedDateExpired();
        }
        // 增加积分
//        memberService.addBonus(order.getUserId(), order.getActualPrice(), order.getOrderSn());
        // 计算佣金
        wxTeamService.benefit(order.getUserId(), order.getActualPrice(), order.getOrderSn());
//        wxBenefitService.team();
        return ResponseUtil.ok();
    }

    /**
     * 删除订单
     * <p>
     * 1. 检测当前订单是否可以删除；
     * 2. 删除订单。
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    public Object delete(Integer userId, String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer orderId = JacksonUtil.parseInteger(body, "orderId");
        if (orderId == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }

        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isDelete()) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "订单不能删除");
        }

        // 订单order_status没有字段用于标识删除
        // 而是存在专门的delete字段表示是否删除
        orderService.deleteById(orderId);
        // 售后也同时删除
        aftersaleService.deleteByOrderId(userId, orderId);

        return ResponseUtil.ok();
    }

    /**
     * 待评价订单商品信息
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @param goodsId 商品ID
     * @return 待评价订单商品信息
     */
    public Object goods(Integer userId, Integer orderId, Integer goodsId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgument();
        }

        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.findByOidAndGid(orderId, goodsId);
        int size = orderGoodsList.size();

        Assert.state(size < 2, "存在多个符合条件的订单商品");

        if (size == 0) {
            return ResponseUtil.badArgumentValue();
        }

        LitemallOrderGoods orderGoods = orderGoodsList.get(0);
        return ResponseUtil.ok(orderGoods);
    }

    /**
     * 评价订单商品
     * <p>
     * 确认商品收货或者系统自动确认商品收货后7天内可以评价，过期不能评价。
     *
     * @param userId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    public Object comment(Integer userId, String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        Integer orderGoodsId = JacksonUtil.parseInteger(body, "orderGoodsId");
        if (orderGoodsId == null) {
            return ResponseUtil.badArgument();
        }
        LitemallOrderGoods orderGoods = orderGoodsService.findById(orderGoodsId);
        if (orderGoods == null) {
            return ResponseUtil.badArgumentValue();
        }
        Integer orderId = orderGoods.getOrderId();
        LitemallOrder order = orderService.findById(userId, orderId);
        if (order == null) {
            return ResponseUtil.badArgumentValue();
        }
        Short orderStatus = order.getOrderStatus();
        if (!OrderUtil.isConfirmStatus(order) && !OrderUtil.isAutoConfirmStatus(order)) {
            return ResponseUtil.fail(ORDER_INVALID_OPERATION, "当前商品不能评价");
        }
        if (!order.getUserId().equals(userId)) {
            return ResponseUtil.fail(ORDER_INVALID, "当前商品不属于用户");
        }
        Integer commentId = orderGoods.getComment();
        if (commentId == -1) {
            return ResponseUtil.fail(ORDER_COMMENT_EXPIRED, "当前商品评价时间已经过期");
        }
        if (commentId != 0) {
            return ResponseUtil.fail(ORDER_COMMENTED, "订单商品已评价");
        }

        String content = JacksonUtil.parseString(body, "content");
        Integer star = JacksonUtil.parseInteger(body, "star");
        if (star == null || star < 0 || star > 5) {
            return ResponseUtil.badArgumentValue();
        }
        Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture");
        List<String> picUrls = JacksonUtil.parseStringList(body, "picUrls");
        if (hasPicture == null || !hasPicture) {
            picUrls = new ArrayList<>(0);
        }

        // 1. 创建评价
        LitemallComment comment = new LitemallComment();
        comment.setUserId(userId);
        comment.setType((byte) 0);
        comment.setValueId(orderGoods.getGoodsId());
        comment.setStar(star.shortValue());
        comment.setContent(content);
        comment.setHasPicture(hasPicture);
        comment.setPicUrls(picUrls.toArray(new String[]{}));
        commentService.save(comment);

        // 2. 更新订单商品的评价列表
        orderGoods.setComment(comment.getId());
        orderGoodsService.updateById(orderGoods);

        // 3. 更新订单中未评价的订单商品可评价数量
        Short commentCount = order.getComments();
        if (commentCount > 0) {
            commentCount--;
        }
        order.setComments(commentCount);
        orderService.updateWithOptimisticLocker(order);

        return ResponseUtil.ok();
    }

    public void doRefund(LitemallOrder order) {
        if (order == null) {
            return;
        }

        // 如果订单不是退款状态，则不能退款
        if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
            return;
        }

        if (order.getPayId() != null) {// 微信退款
            WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
            wxPayRefundRequest.setOutTradeNo(order.getOrderSn());
            wxPayRefundRequest.setOutRefundNo("refund_" + order.getOrderSn());
            // 元转成分
            Integer totalFee = order.getActualPrice().multiply(new BigDecimal(100)).intValue();
            wxPayRefundRequest.setTotalFee(totalFee);
            wxPayRefundRequest.setRefundFee(totalFee);

            WxPayRefundResult wxPayRefundResult;
            try {
                wxPayRefundResult = wxPayService.refund(wxPayRefundRequest);
            } catch (WxPayException e) {
                logger.error(e.getMessage(), e);
                return;
            }
            if (!wxPayRefundResult.getReturnCode().equals("SUCCESS")) {
                logger.warn("refund fail: " + wxPayRefundResult.getReturnMsg());
                return;
            }
            if (!wxPayRefundResult.getResultCode().equals("SUCCESS")) {
                logger.warn("refund fail: " + wxPayRefundResult.getReturnMsg());
                return;
            }
            order.setRefundType("微信退款接口");
            order.setRefundContent(wxPayRefundResult.getRefundId());
        } else { // 余额退款
            userService.addBalance(order.getUserId(), order.getActualPrice(), BalanceConstant.REFUND);
        }


        LocalDateTime now = LocalDateTime.now();
        // 设置订单取消状态
        order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM);
        order.setEndTime(now);
        // 记录订单退款相关信息
        order.setRefundAmount(order.getActualPrice());
        order.setRefundTime(now);
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Integer productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (productService.addStock(orderGoods.getGoodsId(), number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }
    }

    @Override
    public PayInfo checkPayInfo(Integer userId, Integer id) {
        LitemallOrder order = orderService.findById(userId, id);
        if (order == null) {
            return null;
        }
        if (!order.getUserId().equals(userId)) {
            return null;
        }

        if (order.getType().equals(2)) {
            LitemallRentOrder rentOrder = rentOrderService.queryByUserIdAndStatus(userId);
            if (rentOrder == null) {
                return null;
            }
            List<LitemallRentOrderDetail> rentOrderDetails = rentOrderDetailService.queryByOid(rentOrder.getId());
            List<LitemallOrderGoods> orderGoods = orderGoodsService.queryByOid(id);
            for (LitemallOrderGoods orderGood : orderGoods) {
                Integer productId = orderGood.getProductId();
                boolean b = rentOrderDetails.stream().anyMatch(rentOrderDetail -> rentOrderDetail.getGoodsProductId().equals(productId));
                if (!b) {
                    return null;
                } else {
                    boolean b1 = rentOrderDetailService.findByProductId(productId).getNumber().compareTo(orderGood.getNumber()) < 0;
                    if (b1) {
                        return null;
                    }
                }

            }
        }

        // 检测是否能够取消
        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isPay()) {
            return null;
        }

        PayInfo payInfo = new PayInfo();
        payInfo.setOrderSn(order.getOrderSn());
        payInfo.setPrice(order.getActualPrice());
        return payInfo;
    }

    public Object getExpressTrace(Integer orderId) {
        LitemallOrder order = orderService.findById(orderId);
        if (order == null) {
            return ResponseUtil.fail(400, "该订单不存在");
        }
        if (order.getShipWay().equals(1)) {
            return ResponseUtil.ok("同城配送，今日必达！");
        }
        try {
            return ResponseUtil.ok(kdniaoService.getOrderTracesByJson(new Order(order.getId().toString(), order.getShipChannel(), order.getShipSn())));
        } catch (Exception e) {
            return ResponseUtil.fail(500, "获取物流轨迹失败");
        }
    }


}
